/*
 * IBM Corporation.
 * Copyright (c) 2014 All Rights Reserved.
 */

package com.ibm.iisp.dataie.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.ibm.iisp.common.exception.I18nAppException;
import com.ibm.iisp.common.util.BeanFactory;
import com.ibm.iisp.common.util.FileStoreUtils;
import com.ibm.iisp.dataie.model.DataIETemplate;
import com.ibm.iisp.dataie.vo.DataExportRequest;

/**
 * 类作用：定制的模板数据导出
 * 
 * @author Johnny@cn.ibm.com 使用说明：
 */
public class CustomExcelDataExporter extends ExcelDataExporter {
	/**
	 * @param dataExportReq
	 * @param dao
	 */
	public CustomExcelDataExporter(DataExportRequest dataExportReq, EntityManager dao) {
		super(dataExportReq, dao);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ibm.iisp.dataie.service.AbstractDataExporter#init(com.ibm.iisp.dataie.model.DataExportRequest)
	 */
	@Override
	public String init() throws I18nAppException {
		parseFilterParams();
		BeanFactory beanFactory = BeanFactory.getInstance();
		FileStoreUtils fileStoreUtils = beanFactory.getBean(FileStoreUtils.class);
		DataIETemplate tmpl;
		if (dataExportReq.getTemplateId() == null) {
			TypedQuery<DataIETemplate> query = dao.createNamedQuery(DataIETemplate.QUERY_BY_TABLE, DataIETemplate.class)
				.setParameter("tableName", dataExportReq.getTableName());
			List<DataIETemplate> list = query.getResultList();
			if (list.isEmpty()) {
				throw new I18nAppException("IISP_DATA_NO_TEMPLATE", new String[] { "No template file." }, "无模板文件");
			}
			tmpl = list.get(0);
		} else {
			tmpl = dao.find(DataIETemplate.class, dataExportReq.getTemplateId());
		}
		try {
			String fn = tmpl.getFileUri();
			String dName = dataExportReq.getFileName();
			if (StringUtils.isNotEmpty(dName)) {
				// 如果没有扩展名，则加上
				if (dName.indexOf(".") < 0) {
					dName += fn.substring(fn.lastIndexOf("."));
				}
				dName = DATA_EXP_FILE_ROOT + "/" + dName;
			} else {
				dName = DATA_EXP_FILE_ROOT;
			}
			fn = fileStoreUtils.copyFile(fn, dName, true);
			log.info("Template file: {}", fn);
			dataFile = new File(fileStoreUtils.getAbsFilePath(fn));

			try (FileInputStream is = new FileInputStream(dataFile)) {

				if (fn.endsWith(".xls")) {
					book = new HSSFWorkbook(is);
				} else if (fn.endsWith(".xlsx") || fn.endsWith(".xlsm")) {
					book = new XSSFWorkbook(is);
				} else {
					throw new I18nAppException("IISP_DATA_WRONG_TEMPLATE", new String[] { "Not spreadsheet file." }, "非法电子表格文件");
				}

				// verifyDataFile(dataImport, wb);

				return fn;
			}
		} catch (IOException e) {
			log.error("Failed to write data file.", e);
			throw new I18nAppException("IISP_DATA_WRITE_FILE", new String[] { tmpl.getFileUri() },
				"Error to write file:" + tmpl.getFileUri(), e);

		}
	}

}
